# -*- coding: utf-8 -*- 

import os
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
import datetime
import StringIO
import logging

# Third party imports
import json

import urllib2

region_dict = {
    'en-US': 'United States', 
    'en-GB': 'United Kingdom', 
    'en-AU': 'Australia',
    'zh-CN': 'China',
    'ja-JP': 'Japan',
    'en-NZ': 'New Zealand',
    'de-DE': 'Germany',
    'en-CA': 'Canada',
    'fr-FR': 'France'
    }

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
    
class BingImage(db.Model):
    url = db.StringProperty()
    country_region = db.StringProperty()
    name = db.StringProperty()
    copy_info = db.StringProperty()
    date = db.StringProperty()
    create_time = db.DateTimeProperty(auto_now_add=True)    
     
class MainPage(webapp.RequestHandler):
    def get(self):
          self.response.out.write("<html><body>")
          greetings = self.get_greetings()
          stats = memcache.get_stats()

          self.response.out.write("<b>Cache Hits:%s</b><br>" % stats['hits'])
          self.response.out.write("<b>Cache Misses:%s</b><br><br>" %
                                  stats['misses'])
          self.response.out.write(greetings)
          self.response.out.write("""
                <form action="/sign" method="post">
                  <div><textarea name="content" rows="3" cols="60"></textarea></div>
                  <div><input type="submit" value="Sign Guestbook"></div>
                </form>
              </body>
            </html>""")

    def get_greetings(self):
        """
        get_greetings()
        Checks the cache to see if there are cached greetings.
        If not, call render_greetings and set the cache

        Returns:
           A string of HTML containing greetings.
        """
        greetings = memcache.get("greetings")
        if greetings is not None:
            return greetings
        else:
            greetings = self.render_greetings()
            if not memcache.add("greetings", greetings, 10):
                logging.error("Memcache set failed.")
            return greetings

    def render_greetings(self):
        """
        render_greetings()
        Queries the database for greetings, iterate through the
        results and create the HTML.

        Returns:
           A string of HTML containing greetings
        """
        results = db.GqlQuery("SELECT * "
                              "FROM Greeting "
                              "ORDER BY date DESC").fetch(10)
        output = StringIO.StringIO()
        for result in results:
            if result.author:
                output.write("<b>%s</b> wrote:" % result.author.nickname())
            else:
                output.write("An anonymous person wrote:")
            output.write("<blockquote>%s</blockquote>" %
                         cgi.escape(result.content))
        return output.getvalue()

class Guestbook(webapp.RequestHandler):
    def post(self):
        greeting = Greeting()

        if users.get_current_user():
            greeting.author = users.get_current_user()

        greeting.content = self.request.get('content')
        greeting.put()
        self.redirect('/')
        
class ApiServer(webapp.RequestHandler):
 
    def get(self):

        try:
            token = self.request.headers['FM-Auth-Token']
        except KeyError:
            self.error(401) # Unauthorized
            return
        
        if token != "24b7a7ab83ad189447f093fe0fca97b9":
            self.error(401) # Unauthorized
            return
            
        d = self.request.get("date")
        r = self.request.get("region")
        debug = self.request.get("debug")
        
        if not r:
            r = "all"
        if not d:
            d = "today"

        images = self.get_bingimages(d, r)
        
        self.response.headers['Content-Type'] = 'application/json; charset=utf-8'        
        if debug == "y":
            stats = memcache.get_stats()

            self.response.out.write("<b>Cache Hits:%s</b><br>" % stats['hits'])
            self.response.out.write("<b>Cache Misses:%s</b><br><br>" %
                                  stats['misses'])
            self.response.out.write(token)
        #self.response.out.write(json.write(images))
        self.response.out.write(json.write(images))  
    
    def get_bingimages(self, date, region):
        bingimage = memcache.get(date + region)
        if bingimage is not None:
            return bingimage
        else:
            bingimage = BingImage.all()
            images = []
            if region != "all":
                bingimage.filter("country_region = ", region_dict[region])
                
            if date == "today":
                bingimage.filter("date = ", datetime.date.today().isoformat())
            else:
                bingimage.filter("date = ", date)
                
            for image in bingimage:
                item = {'key' : str(image.key()),
                      'url' : image.url,
                      'country_region' : image.country_region,
                      'copy_info' : image.copy_info,
                      'date' : image.date,
                      'name' : image.name,
                      }
                images.append(item)
            if not memcache.add(date + region, images, 3600):
                logging.error("Memcache set failed.")
            return images
        
class Fetch(webapp.RequestHandler):
    def get(self):
        q = BingImage.all().filter("date = ", datetime.date.today().isoformat())

        if q.count() == 0:
            self.Fetch_worker()
        else:
            self.response.out.write("Already finish the fetching work!<br/>")
        
    def Fetch_worker(self):
        bing_site_list = [
            ["http://www.bing.com/?scope=web&setmkt=en-US", "United States"],
            ["http://www.bing.com/?scope=web&setmkt=en-GB", "United Kingdom"],
            ["http://www.bing.com/?scope=web&setmkt=en-AU", "Australia"],
            ["http://www.bing.com/?scope=web&setmkt=zh-CN", "China"],
            ["http://www.bing.com/?scope=web&setmkt=ja-JP", "Japan"],
            ["http://www.bing.com/?scope=web&setmkt=en-NZ", "New Zealand"],
            ["http://www.bing.com/?scope=web&setmkt=de-DE", "Germany"],
            ["http://www.bing.com/?scope=web&setmkt=en-CA", "Canada"],
            ["http://www.bing.com/?scope=web&setmkt=fr-FR", "France"],
        ]
        L = []
                      
        for bing_site in bing_site_list:
            result = urllib2.urlopen( bing_site[0]).read()
            tempStr = result[result.index('g_img={url:')+12 : len(result)]
            tempStr = tempStr[0 : tempStr.index(',id:')-1]
            tempStr = tempStr.replace('\\', '')
            bgImageUrl = 'http://www.bing.com' + tempStr
            image_name = tempStr.split("/")[-1].split("_")[0]
            
            tempStr = result[result.index('copy') : len(result)]
            copy_info = tempStr[tempStr.index('<p>')+3:tempStr.index('</p>')]
            
            image = BingImage()
            image.url = bgImageUrl
            image.country_region = bing_site[1]
            image.name = image_name
            image.copy_info = unicode(copy_info, "utf-8")
            image.date = datetime.date.today().isoformat()
            #copy_info.decode('utf-8')
            image.put()
            L.append(image.to_xml())
            
        self.response.headers['Content-Type'] = 'text/html;charset=unicode'
        self.response.out.write("<br/>".join(L))
        mail.send_mail(sender="LBI <franksunye@gmail.com>",
            to="fu@fotomesh.com,ye@fotomesh.com",
            subject="Love Bing Image Daily working report " + datetime.date.today().isoformat(),
            body="<br/>".join(L)
            )
    
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/image', ApiServer),
                                      ('/fetch', Fetch),
                                      ('/sign', Guestbook)
                                      ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
